using Tycho.Compiler;

namespace Tycho.Runtime {
    public class NonRecursiveModuleLoader : IModuleScopeLoader {
        private Namespace NamespaceToBlock;
        private IModuleScopeLoader Loader;
        private readonly bool includeNestedNamespaces;

        public NonRecursiveModuleLoader (Namespace namespaceToBlock, IModuleScopeLoader loader) : this (namespaceToBlock, loader, false) {
        }

        public NonRecursiveModuleLoader (Namespace namespaceToBlock, IModuleScopeLoader loader, bool includeNestedNamespaces) {
            NamespaceToBlock = namespaceToBlock;
            Loader = loader;
            this.includeNestedNamespaces = includeNestedNamespaces;
        }

        public SymbolScope LoadModule (Namespace ns) {
            if (!IsNamespaceBlocked (ns)) {
                return Loader.LoadModule (ns);
            } else {
                return null;
            }
        }

        private bool IsNamespaceBlocked (Namespace ns) {
            var blocked = ns == NamespaceToBlock;

            if (blocked) {
                return true;
            } else if (includeNestedNamespaces && ns.Parent != null) {
                return IsNamespaceBlocked (ns.Parent);
            } else {
                return false;
            }
        }
    }
}